package Thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author: lqh
 * @description: 有三个跑步运动员，各自准备好后等待其他人，全部准备好后才开始跑
 * (CyclicBarrier用于处理多个线程互相等待的情况)
 * @program: Demo
 * @create: 2018-04-14 14:54
 **/
public class demo4 {
    public static void main(String[] args) {
        String[] threadArr = {"A","B","C"};
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        for (int i=0;i<threadArr.length;i++){
            String threadName = threadArr[i];
            new Thread(new Runnable() {
                @Override
                public void run() {
                    long time = new Random().nextInt(1000)+100;
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        System.out.println(threadName+"准备了"+time+"ms");
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                    System.out.println(threadName+"开始跑步了"+System.currentTimeMillis());

                }
            }).start();
        }
    }
}
